<template>
  <div ref="chart" class="chart" />
</template>

<script>
import * as echarts from 'echarts'
import resize from '@/mixins/resize'

export default {
  name: 'Trend',
  mixins: [resize],
  props: {
    activeTab: {
      type: String,
      required: true
    }
  },
  mounted() {
    const myEcharts = echarts.init(this.$refs.chart)

    const name = this.activeTab === 'sales' ? '销售量' : '访问量'

    const option = {
      title: {
        text: `${name}趋势`
      },
      xAxis: {
        data: [
          '一月',
          '二月',
          '三月',
          '四月',
          '五月',
          '六月',
          '七月',
          '八月',
          '九月',
          '十月',
          '十一月',
          '十二月'
        ]
      },
      yAxis: {},
      series: {
        name,
        type: 'bar',
        data: [20, 55, 44, 85, 78, 62, 99, 28, 70, 85, 78, 62],
        barWidth: '40%' // 柱条的宽度
        // showBackground: true
      },
      grid: {
        left: 0,
        right: 0,
        bottom: 0,
        containLabel: true
      },
      tooltip: {
        // 添加一个指示器
        trigger: 'axis',
        axisPointer: {
          type: 'line',
          lineStyle: {
            width: '80',
            color: 'rgba(0, 0, 0, .1)'
          }
        }
      }
    }

    myEcharts.setOption(option)

    this.myEcharts = myEcharts
  },
  watch: {
    activeTab(activeTab) {
      const name = activeTab === 'sales' ? '销售量' : '访问量'
      // 随机数据
      const data = []
      for (let i = 0; i < 12; i++) {
        data.push(Math.round(Math.random() * 80 + 20))
      }

      // 渲染新的图表
      // 只需要将要更新的部分传入，其他部分会用之前的值
      this.myEcharts.setOption({
        title: {
          text: `${name}趋势`
        },
        series: {
          name,
          data
        }
      })
    }
  }
}
</script>

<style scoped>
.chart {
  width: 100%;
  height: 300px;
}
</style>
